/****************************************************
	文件：CsvHandler.cs
	作者：HuskyT
	邮箱：1005240602@qq.com
	日期：2020/9/21 13:43:54
	功能：Csv 处理器 （处理一个Csv任务）
*****************************************************/

using System.Collections.Generic;
using System.IO;
using System.Text;
using OfficeOpenXml;

namespace HTFW.Scheme
{
    public class CsvHandler
    {
        private string mPath;
        private Dictionary<int, List<string>> mSheet;

        public CsvHandler(string path)
        {
            mPath = path;
            LoadData();
        }

        private void LoadData()
        {
            mSheet = new Dictionary<int, List<string>>();
            int rowIndex = 0;
            foreach (string line in File.ReadLines(mPath))
            {
                string[] strArray = line.Split(',');
                List<string> rowData = new List<string>();
                foreach (string item in strArray)
                {
                    rowData.Add(item);
                }

                mSheet.Add(rowIndex, rowData);
                rowIndex++;
            }
        }

        public void ToExcel(string excelPath, Encoding encoding)
        {
            if (File.Exists(excelPath)) File.Delete(excelPath);
            using (ExcelPackage ep = new ExcelPackage(new FileInfo(excelPath)))
            {
                //创建ExcelWorkSheet对象，这个对象就是面对表的，是工作簿中单个表
                ExcelWorksheet excelSheet = ep.Workbook.Worksheets.Add("Sheet1");
                for (int i = 0; i < mSheet.Count; i++)
                {
                    for (int j = 0; j < mSheet[0].Count; j++)
                    {
                        excelSheet.Cells[i + 1, j + 1].Value = mSheet[i][j];
                    }
                }

                ep.Save();
            }
        }
    }
}